#include "CNetService.h"
#include "CNetServiceImpl.h"
#include "../coroutine.h"

namespace TB
{
	CNetService::CNetService() :
		m_poImpl(std::make_shared<CNetServiceImpl>())
	{
	}

	CNetService::~CNetService()
	{
		Close();
	}

	bool CNetService::Init(const std::weak_ptr<CCoroutine>& poCoroutine, const std::function<void(INT32)>& rcbOnPollError)
	{
		std::weak_ptr<CNetServiceImpl> poSelf = m_poImpl;
		return m_poImpl->Init(poCoroutine, rcbOnPollError, poSelf);
	}

	std::weak_ptr<CCoroutine>& CNetService::GetCoroutine()
	{
		return m_poImpl->GetCoroutine();
	}

	const std::weak_ptr<CCoroutine>& CNetService::GetCoroutine() const
	{
		return m_poImpl->GetCoroutine();
	}

	void CNetService::Close()
	{
		auto poCoroutine = GetCoroutine().lock();
		if (!poCoroutine || CCoroutine::GetCurrent() == poCoroutine)
		{
			m_poImpl->Close();
		}
		else
		{
			std::shared_ptr<CNetServiceImpl> poImpl = m_poImpl;
			poCoroutine->Post([poImpl]() mutable
			{
				poImpl->Close();
			});
		}
	}
}